﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LearningEnglish.Controllers
{
    /// <summary>
    /// 为普通Api，在返回值的处理，以及异常的处理中，提供一般处理方法 
    /// </summary>
    public class NormalJsonAttribute : HandleErrorAttribute
    {
        public NormalJsonAttribute()
        {
            Order = 1;
        }

        public override void OnException(ExceptionContext filterContext)
        {
            //如果不是500之类的错误，而是什么  “404没发现” 之类的错误，那就不要管它，让其它异常代码处理它，显示给用户看
            if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
            {
                return;
            }

            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];

            //记录错误，并防止记录时的异常
            try
            {
                var mistake = filterContext.Exception as MyX.Core.XMistake;
                if (mistake != null)
                {
                    //LogHelper.WriteLog("DoJson : 错误 ， " + mistake.Message);
                }
                else
                {
                    //LogHelper.WriteLog("异常： " + controllerName + "  ,  " + actionName);
                    //LogHelper.WriteLog(filterContext.Exception);
                }
            }
            catch (Exception)
            {

            }


            filterContext.Result = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    error = true,
                    msg = filterContext.Exception.Message
                }
            };

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;


            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;


        }
    }
}